// pages/purchase-list/purchase-list.js
const app = getApp()
import util from "../../utils/util.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderList: [],
    activeNames: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    activeNames2: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    result: [],
    checked: false,
    revise: false,
    currentDate: new Date().getTime() + 86400000,
    applyType: 0,
    allowApply:true,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const {
      revise=false,
      stockOrderId = 0,
      auxiliaryMaterialsId = 0,
      smallCanteenPurchaseId = 0,
      collarId=0,
      estimatedTime,
      estimatedNum,
      applyType,
      orderList,
      canteensList
    } = app.globalData
    if (applyType == 0) {
      this.setData({ orderId: stockOrderId })
    } else if (applyType == 1) {
      this.setData({ orderId: auxiliaryMaterialsId })
    } else if (applyType == 2) {
      this.setData({ orderId: smallCanteenPurchaseId })
    } else {
      this.setData({ orderId: collarId })
    }
    this.setData({
      revise,
      estimatedTime,
      estimatedNum,
      applyType,
 
    })

    if (revise){
      this.setData({
        orderList, estimatedTime,
        canteensList,
        estimatedNum,},()=>{

          if (applyType===0){
            this.rgetDetails(stockOrderId)
          } else if (applyType === 1) {
            // this.rgetDetails(stockOrderId)
          } else if (applyType === 2) {
            this.rgetDetails2(smallCanteenPurchaseId)
          } else  {
            this.rgetDetails3(collarId)
          }


        })

        


    }else{
      this.getDetails(applyType)
    }
    
  },
  getDetails(applyType){
    app.reqFetch.temporaryordermxgetTemOrdermx({
      sign: applyType,
    }, (res) => {
      const { list, temOrder}=res.data
      if (temOrder.boxId){
        this.setData({ canteensList: JSON.parse(temOrder.boxId).list})
      }
      this.setData({ 
        orderList: list,
        temOrder,
        estimatedNum: temOrder.estimateNum,
        estimatedTime: temOrder.mealTime,
     
       })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  handelShowDate() {
    if (revise){
      return
    }
    this.setData({ dateShow: true })
  },
  onClose() {
    this.setData({ dateShow: false })
  },
  dateConfirm(e) {
    let estimatedTime = util.formatTime(new Date(e.detail)).substring(0, 16)
    const { temOrder, applyType}=this.data
  
    this.setData({ estimatedTime,dateShow: false })
    app.reqFetch.temporaryorderupdeteOrder({
      mealTime:estimatedTime,
       temporaryId : temOrder.temporaryId,
      sign: applyType
    }, (res) => {
    })

  },
  numChnage(e) {
    this.setData({ estimatedNum: e.detail.value })

  },
  numConfirm(){

    const { temOrder, estimatedNum, applyType} = this.data
    app.reqFetch.temporaryorderupdeteOrder({
      estimateNum: estimatedNum,
      temporaryId: temOrder.temporaryId,
      sign: applyType
    }, (res) => {
    })
  },
  formatDate(date) {
    date = new Date(date)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return year + '-' + month + '-' + day
  },
  /**
   * 生命周期函数--监听页面显示
   */

  rgetDetails(stockOrderId) {
    app.reqFetch.getOrderDetails({
      stockOrderId
    }, (res) => {
      const {
        stockorder,
        list
      } = res
      const {
        mealTime,
        estimateNum,
        stockOrderId
      } = stockorder
      let orderList = []
      list.map(item => {
        orderList.push({
          supplierId: item.gysId,
          supplierName: item.gys,
          foods: item.mxlist
        })
      })
      app.globalData.orderList = orderList
      app.globalData.estimatedTime = mealTime
      app.globalData.estimatedNum = estimateNum
      this.setData({ orderList })
    })
  },
  rgetDetails2(smallCanteenPurchaseId) {
    app.reqFetch.smallcanteenpurchasemxdetails({
      smallCanteenPurchaseId
    }, (res) => {
      const {
        smallCanteenPurchase,
        list
      } = res

      const {
        boxId,
        smallCanteenPurchaseId
      } = smallCanteenPurchase
      let orderList = []
      list.map(item => {
        orderList.push({
          supplierId: item.gysId,
          supplierName: item.gys,
          foods: item.mxlist
        })
      })

      app.globalData.canteensList = JSON.parse(boxId).list
      app.globalData.orderList = orderList
      this.setData({ orderList})
    })
  },
  rgetDetails3(collarId) {
    app.reqFetch.collarmxdetails({
      collarId,
      type:2
    }, (res) => {
      const {
        collar,
        collarMx
      } = res
      let orderList = []

      orderList.push({
        supplierName: "主食领取清单",
        foods: collarMx
      })

      app.globalData.orderList = orderList
      this.setData({ orderList })
    })

  },
  rgetDetails4(auxiliaryMaterialsId) {
    app.reqFetch.auxiliarymaterialsmxDetails({ auxiliaryMaterialsId }, (res) => {
      const { list } = res
      const { type } = this.data
      let orderList = []
      list.map(item => {
        orderList.push({ supplierId: item.gysId, supplierName: item.gys, foods: item.mxlist })
      })
      app.globalData.orderList = orderList
      this.setData({ orderList })

    })

  },



  onShow: function() {


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  addMore() {
    wx.reLaunch({
      url: '/pages/supply-menu/supply-menu',

    })
  },
  changeCollapse(event) {

    this.setData({
      activeNames: event.detail
    });
  },
  changeCollapse2(event) {
    this.setData({
      activeNames2: event.detail
    });
  },


  checkItem(event) {
    this.setData({
      result: event.detail
    });
  },
  delFoods() {
    let {
      result,
      orderList,
      applyType
    } = this.data
    if (!result.length){
        return
    }
    result.map(item => {
      const [supplierId=0, foodId] = item.split(',')
      let params = {
        sign: applyType,
        foodId,
      }
      if (applyType!==3){
        params.supplierId = supplierId
      }
    
      if (app.globalData.revise) {
        params.orderId = this.data.orderId
      }
      app.reqFetch.deleteFood({
        ...params
      }, (res) => {
      })

      if (applyType == 3) {
        orderList.map(item => {
        
            if (item.foods) {
              item.foods = this.removeAaary(item.foods, item.foods.filter(ele => ele.foodId === foodId)[0])

            }
          
        })
      }

      orderList.map(item => {
        if (item.supplierId === supplierId) {
          if (item.foods) {
            item.foods = this.removeAaary(item.foods, item.foods.filter(ele => ele.foodId === foodId)[0])

          }
        }
      })
    })
    orderList.map(item => {
      if (item.foods.length === 0) {
        orderList = this.removeAaary(orderList, item)
      }
    })
    this.setData({
      orderList,
      result:[],
      checked: false
    })
  },

  removeAaary(_arr, _obj) {
    var length = _arr.length;
    for (var i = 0; i < length; i++) {
      if (_arr[i] == _obj) {
        if (i == 0) {
          _arr.shift(); //删除并返回数组的第一个元素
          return _arr;
        } else if (i == length - 1) {
          _arr.pop(); //删除并返回数组的最后一个元素
          return _arr;
        } else {
          _arr.splice(i, 1); //删除下标为i的元素
          return _arr;
        }
      }
    }
  },

  changeNum(e) {
    const {
      supplierId
    } = e.currentTarget.dataset.record
    const {
      foodId
    } = e.currentTarget.dataset.curr
    let {
      orderList,
      applyType
    } = this.data

    orderList.map(item => {
      if (item.supplierId === supplierId) {
        item.foods.map(ele => {
          if (ele.foodId === foodId) {
            let params = {
              sign: applyType,
              foodId,
              supplierId,
              purchaseNum: e.detail}
            if (app.globalData.revise) {
              params.orderId = this.data.orderId
            }
            app.reqFetch.updateFood({
              ...params
            }, (res) => {
            })


            ele.purchaseNum = e.detail
          }
        })
      }
    })
    this.setData({
      orderList
    })
  },
  checkAll(e) {
    let {
      orderList
    } = this.data

    this.setData({
      checked: e.detail
    });
    if (e.detail) {
      var arr = []
      orderList.map(item => {
        item.foods.map(ele => {
          arr.push(item.supplierId + ',' + ele.foodId)
        })
      })

      this.setData({
        result: arr
      });
    } else {
      this.setData({
        result: []
      });
    }
  },



  createOrder() {
    if (!this.data.allowApply){
      return
    }
    this.setData({ allowApply:false})
    const {
      
      applyType,
      revise
    } = app.globalData

    const userId= wx.getStorageSync('userId')
    const {
      orderList,
      estimatedTime,
      estimatedNum,
      stockOrderId,
      auxiliaryMaterialsId
    } = this.data
    if (orderList.length<=0){
      wx.showToast({
        title: '您还未选择菜品',
        icon:'none'
      })
      return
    }

    if (revise) {
      this.returnHome()
      // const {
      //   estimatedTime,
      //   estimatedNum,
      //   stockOrderId,
      //   auxiliaryMaterialsId,
      //   smallCanteenPurchaseId,
      //   collarId
      // } = app.globalData
      // const { canteensList,}=this.data
      // app.globalData.revise = false
      // if (applyType == 0) {
      //   app.reqFetch.saveOrder({
      //     chedId: userId,
      //     mealTime: estimatedTime,
      //     estimateNum: estimatedNum.toString(),
      //     stockOrderId,
      //     list: orderList
      //   }, res => {
      //     this.returnHome()
      //   })
      // } else if (applyType === 1) {
      //   app.reqFetch.saveAuxiliaryOrder({
      //     chedId: userId,
      //     list: orderList,
      //     auxiliaryMaterialsId
      //   }, res => {
          
      //     wx.showToast({
      //       title: '提交成功',
      //       icon: 'none'
      //     })
      //     setTimeout(function() {
      //       wx.reLaunch({
      //         url: '/pages/warehouse-home/warehouse-home?data=' + JSON.stringify({ type: applyType }),
      //       })
      //     }, 700);
      //   })
        
      // } else if (applyType === 2){
      //   app.reqFetch.smallsaveAuxiliaryOrder({
      //     boxId: JSON.stringify({
      //       ...canteensList
      //     }),
      //     mealTime: canteensList.date,
      //     smallCanteenPurchaseId,
      //     chedId: userId,
      //     list: orderList
      //   }, res => {
      //     this.returnHome()
      //   })
      // }else{
      //   app.reqFetch.saveCollarOrder({
      //     collarId,
      //     chedId: userId,
      //     list: orderList
      //   }, res => {
      //     this.returnHome()
      //   })
      // }
    } else {
      if (applyType === 0) {
        app.reqFetch.saveOrder({
          chedId: userId,
          mealTime: estimatedTime,
          estimateNum: estimatedNum,
          list: orderList
        }, res => {
          this.returnHome()
        })
      } else if (applyType === 1) {
        app.reqFetch.saveAuxiliaryOrder({
          chedId: userId,
          
          list: orderList
        }, res => {
          this.returnHome()
 

        })
      } else if (applyType === 2){
        const { canteensList, } = this.data

 
        app.reqFetch.smallsaveAuxiliaryOrder({
          boxId: JSON.stringify({
            list: canteensList
          }),

          mealTime: canteensList.date,
          chedId: userId,
          list: orderList
        }, res => {
          this.returnHome()
        })
      } else {
        
        app.reqFetch.saveCollarOrder({
  
          chedId: userId,
          list: orderList
        }, res => {
          this.returnHome()

        })


      }
      
    }





  },
  reviseInfo(){
    if (app.globalData.revise){
      return
    }
    app.globalData.canteensRevise=true
    const { temOrder, canteensList} = this.data
    wx.navigateTo({
      url: '/pages/chef-canteen/chef-canteen?data=' + JSON.stringify({ temporaryId:temOrder.temporaryId, canteensList }),
    })
  },
  returnHome(){
    const {applyType,} = app.globalData
    wx.showToast({
      title: '提交成功',
      icon: 'none'
    })
    if (applyType===1){
      setTimeout(function () {
        wx.reLaunch({
          url: '/pages/warehouse-home/warehouse-home?data=' + JSON.stringify({ type: applyType }),
        })
      }, 700);
    }else{
      setTimeout(function () {
        wx.reLaunch({
          url: '/pages/chef-home/chef-home?data=' + JSON.stringify({ type: applyType }),
        })
      }, 700);
    }

      
 
  },
  handleCancel(){
    const { applyType, } = app.globalData
    if (applyType===1){
      wx.reLaunch({
        url: '/pages/warehouse-home/warehouse-home?data=' + JSON.stringify({ type: applyType }),
      })
    }else{
      wx.reLaunch({
        url: '/pages/chef-home/chef-home?data=' + JSON.stringify({ type: applyType }),
      })
    }



  }



})